<?php

namespace app\tools;

use phpDocumentor\Reflection\Types\Self_;
use yii\helpers\ArrayHelper;
use Yii;

class Rongyun
{
  //注册用户
  public static function getToken($user_id, $user_name, $user_icon) {
    $url = "http://api-cn.ronghub.com/user/getToken.json";
    $bodys = "userId=" . $user_id . "&name=" . $user_name . "&portraitUri=" . $user_icon;
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }

  //创建聊天室
  public static function createRyChatRoom($model) {
    $url = "http://api-cn.ronghub.com/chatroom/create.json";
    $bodys = "chatroom[". $model->chat_room_code ."]=" . $model->chat_room_code;
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }

  //查询聊天室
  public static function queryRyChatRoom($chat_room_id) {
    $url = "https://api-cn.ronghub.com/chatroom/query.json";
    $bodys = "chatroomId=" . $chat_room_id;
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }

  //查询聊天室成员
  public static function queryRyChatRoomUser($chat_room_id) {
    $url = "https://api-cn.ronghub.com/chatroom/user/query.json";
    $bodys = "chatroomId=" . $chat_room_id . "&count=500&order=2";
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }


  //销毁聊天室
  public static function destroyRyChatRoom($chat_room_id) {
    $url = "https://api-cn.ronghub.com/chatroom/destroy.json";
    $bodys = "chatroomId=" . $chat_room_id;
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }

  //聊天室禁言
  public static function stopRyChatRoom($chat_room_id) {
    $url = "https://api-cn.ronghub.com/chatroom/message/stopDistribution.json";
    $bodys = "chatroomId=" . $chat_room_id;
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }

  //取消聊天室禁言
  public static function startRyChatRoom($chat_room_id) {
    $url = "https://api-cn.ronghub.com/chatroom/message/resumeDistribution.json";
    $bodys = "chatroomId=" . $chat_room_id;
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }

  //成员禁言
  public static function stopUser($chat_room_id, $user_id, $minute) {
    $url = "https://api-cn.ronghub.com/chatroom/user/gag/add.json";
    $bodys = "userId=" . $user_id . "&chatroomId=" . $chat_room_id. "&minute=" . $minute;
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }

  //成员封禁(踢出聊天室)
  public static function blockUser($chat_room_id, $user_id, $minute) {
    $url = "https://api-cn.ronghub.com/chatroom/user/block/add.json";
    $bodys = "userId=" . $user_id . "&chatroomId=" . $chat_room_id. "&minute=" . $minute;
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }

  //发送文本消息
  public static function sendText($chat_room_id, $from_user_id, $content, $username, $icon, $type, $msg_type='') {
    $url = "https://api-cn.ronghub.com/message/chatroom/publish.json";
    $data = [
      'content' => $content,
      'extra' => [
        'username' => $username,
        'icon' => $icon,
        'type' => $type,
        'msg_type' => $msg_type
      ],
    ];
    $bodys = "content=" . json_encode($data) . "&fromUserId=" . $from_user_id . "&toChatroomId=" . $chat_room_id . "&objectName=RC:TxtMsg";
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }

  //发送图片消息
  public static function sendImg($chat_room_id, $from_user_id, $img_url, $username, $icon, $type) {
    $url = "https://api-cn.ronghub.com/message/chatroom/publish.json";
    $data = [
      //'content' => self::imgToBase64($img_url),
      'imageUri' => $img_url,
      'extra' => [
        'username' => $username,
        'icon' => $icon,
        'type' => $type,
      ],
    ];
    //var_dump(json_encode($data));die;
    $bodys = "content=" . json_encode($data) . "&fromUserId=" . $from_user_id . "&toChatroomId=" . $chat_room_id . "&objectName=RC:ImgMsg";
    //var_dump($bodys);die;
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }

  //发送自定义消息
  public static function sendSettingMsg($chat_room_id, $from_user_id, $content, $obj_name, $username, $validity_time, $icon, $type, $red_packet_id=0, $is_view=0, $block_user_id='') {
    $url = "https://api-cn.ronghub.com/message/chatroom/publish.json";
    $data = [
      'content' => $content,
      'extra' => [
        'username' => $username,
        'icon' => $icon,
        'type' => $type,
        'end_time' => time() + $validity_time * 60,
        'red_packet_id' => $red_packet_id,
        'is_view' => $is_view,
        'block_user_id' => $block_user_id
      ],
    ];
    $bodys = "content=" . json_encode($data) . "&fromUserId=" . $from_user_id . "&toChatroomId=" . $chat_room_id . "&objectName=" . $obj_name;
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }

  //消息撤回
  public static function recallMsg($chat_room_id, $from_user_id, $message_uid, $sent_time) {
    $url = "https://api-cn.ronghub.com/message/recall.json";
    $bodys = "fromUserId=" . $from_user_id . "&conversationType=4&targetId=" . $chat_room_id . "&messageUID=" . $message_uid . "&sentTime=" . $sent_time;
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }

  //检查用户在线状态
  public static function checkOnline($user_id) {
    $url = "https://api-cn.ronghub.com/user/checkOnline.json";
    $bodys = "userId=" . $user_id;
    $res_data = self::httpRequest($url, $bodys);
    return $res_data;
  }

  public static function httpRequest($url, $bodys) {
    $headers = array();
    $rongyun_key = Yii::$app->params['rongyun_key'];
    $rongyun_secret = Yii::$app->params['rongyun_secret'];
    $nonce = rand(); // 获取随机数。
    $timestamp = time()*1000; // 获取时间戳（毫秒）。
    $signature = sha1($rongyun_secret.$nonce.$timestamp);
    array_push($headers, "App-Key: " . $rongyun_key);
    array_push($headers, "Nonce: " . $nonce);
    array_push($headers, "Timestamp: " . $timestamp);
    array_push($headers, "Signature: " . $signature);
    array_push($headers, "Content-Type".":"."application/x-www-form-urlencoded; charset=UTF-8");
    $method = "POST";
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_HEADER, false);
    if (1 == strpos("$".$url, "https://"))
    {
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    }
    $result_data = curl_exec($curl);
    return $result_data;
  }

  public static function imgToBase64($image_file) {
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = file_get_contents($image_file);
    $base64_image = base64_encode($image_data);
    $base64 = str_replace('=', '', $base64_image);
    $img_len = strlen($base64);
    $file_size = $img_len - ($img_len / 8) * 2;
    $file_size = number_format(($file_size / 1024), 2);
    //echo $file_size;die;
    $base64_image = str_replace("\r", "", $base64_image);
    $base64_image = str_replace("\n", "", $base64_image);
    $base64_image = str_replace("\r\n", "", $base64_image);
    return $base64_image;
  }
}
